package com.pay.cloud.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkRequest;

import com.pay.cloud.Application;


public class NetworkService extends IntentService {
    private static boolean started = false;
    private static boolean available = false;
    private static final NetworkCallback callback = new NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            available = true;
        }

        @Override
        public void onLost(Network network) {
            available = false;
        }
    };

    public NetworkService() {
        super("NetworkService");
    }

    public static boolean isNetworkAvailable() {
        if (!available) {
            ConnectivityManager manager = (ConnectivityManager) Application.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null == manager) {
                return false;
            }
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if (null == networkInfo) {
                return false;
            }
            return networkInfo.isAvailable();
        }
        return true;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (started) return;
        started = true;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(new NetworkRequest.Builder().build(), callback);
    }

}
